// https://leetcode-cn.com/problems/trapping-rain-water/

function trap(height: number[]): number {
    const maxIndex = getMaxIndex(height);
    return trapLeft(height, maxIndex) + trapRight(height, maxIndex);

    function trapLeft(height: number[], idx: number): number {
        let sum = 0;
        let max = 0;
        for (let i = 0; i < idx; i++) {
            if (height[i] > max) {
                max = height[i];
                continue;
            }

            sum += max - height[i];
        }
        return sum;
    }
    function trapRight(height: number[], idx: number): number {
        let sum = 0;
        let max = 0;
        for (let i = height.length - 1; i > idx; i--) {
            if (height[i] > max) {
                max = height[i];
                continue;
            }

            sum += max - height[i];
        }
        return sum;
    }

    function getMaxIndex(height: number[]): number {
        let result = 0;
        let max = height[0];
        for (let i = 0; i < height.length; i++) {
            if (height[i] > max) {
                result = i;
                max = height[i];
            }
        }
        return result;
    }
}

console.log(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]));
console.log(trap([4, 2, 0, 3, 2, 5]));
